package com.kaxiu.config.wx.pay;

import com.github.binarywang.wxpay.config.WxPayConfig;
import com.github.binarywang.wxpay.service.WxPayService;
import com.github.binarywang.wxpay.service.impl.WxPayServiceImpl;
import com.google.common.collect.Maps;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author: LiYang
 * @create: 2019-08-18 23:44
 * @Description: <a href="https://github.com/binarywang">Binary Wang</a>
 **/

@Configuration
@EnableConfigurationProperties(WxPayProperties.class)
@ConditionalOnProperty(prefix = "wx.pay", value = "enabled", matchIfMissing = true)
public class WxPayAutoConfiguration {

    private WxPayProperties properties;

    private static Map<String, WxPayService> payServices = Maps.newHashMap();

    @Autowired
    public WxPayAutoConfiguration(WxPayProperties properties) {
        this.properties = properties;
    }

    public static WxPayService getPayService(String appid) {
        WxPayService payService = payServices.get(appid);
        if (payService == null) {
            throw new IllegalArgumentException(String.format("未找到微信支付对应appid=[%s]的配置，请核实！", appid));
        }

        return payService;
    }

    /**
     * 构造微信支付服务对象.
     */
    @PostConstruct
    public void init() {
        List<WxPayProperties.Config> configs = this.properties.getConfigs();

        if (configs == null) {
            throw new RuntimeException("微信支付小程序配置为空！");
        }
        payServices = configs.stream()
            .map(a -> {
                final WxPayServiceImpl wxPayService = new WxPayServiceImpl();
                WxPayConfig payConfig = new WxPayConfig();
                payConfig.setAppId(StringUtils.trimToNull(a.getAppId()));
                payConfig.setMchId(StringUtils.trimToNull(a.getMchId()));
                payConfig.setMchKey(StringUtils.trimToNull(a.getMchKey()));
                payConfig.setSubAppId(StringUtils.trimToNull(a.getSubAppId()));
                payConfig.setSubMchId(StringUtils.trimToNull(a.getSubMchId()));
                payConfig.setKeyPath(StringUtils.trimToNull(a.getKeyPath()));
                wxPayService.setConfig(payConfig);
                return wxPayService;
            }).collect(Collectors.toMap(s -> s.getConfig().getAppId(), a -> a));
    }

}
